package com.ifonly.mvc;

import com.ifonly.aop.Invocation;
import com.ifonly.interceptor.Interceptor;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-10 17:19
 * @since JDK 1.6
 */
public class ActionInvocation extends Invocation {

    private Action action;
    private Controller controller;

    private Interceptor[] interceptors;
    private int size = 0;
    private int index = 0;

    public ActionInvocation(Action action, Controller controller) {
        super(controller, action.getMethod());
        this.action = action;
        this.controller = controller;
        Interceptor[] temp = this.action.getInterceptors();
        if (temp != null) {
            this.size = temp.length;
            this.interceptors = temp;
        } else {
            this.interceptors = new Interceptor[0];
        }
    }

    @Override
    public void invoke() {
        try {
            if (index < size) {
                Interceptor interceptor = interceptors[index++];
                interceptor.intercept(this);
            } else {
                method.invoke(controller);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Controller getController() {
        return controller;
    }
}
